const cookieparser = process.server ? require("cookieparser") : undefined;
const Cookie = process.client ? require("js-cookie") : undefined;
import { updateUser } from "@/api/user";

export const state = () => {
  return {
    user: null,
    articleAuthor: null,
  };
};

export const mutations = {
  setUser(state, payload) {
    state.user = payload;
  },
  setArticleAuthor(state, payload) {
    state.articleAuthor = payload;
  },
  updateUserInfo(state, payload) {
    state.user = Object.assign({}, state.user, payload);
    if (Cookie) {
      // 客户端执行操作cookie代码
      Cookie.set("user", state.user);
    }
  },

  cleanUser(state) {
    state.user = null;
    Cookie.remove("user");
  },
};

export const actions = {
  nuxtServerInit({ commit }, { req }) {
    let user = null;
    let articleAuthor = null;
    if (req.headers.cookie) {
      const parsed = cookieparser.parse(req.headers.cookie);
      try {
        user = JSON.parse(parsed.user);
        articleAuthor = parsed.articleAuthor
          ? JSON.parse(parsed.articleAuthor)
          : null;
      } catch (err) {}
    }
    commit("setUser", user);
    commit("setArticleAuthor", articleAuthor);
  },
  async updateUserState({ commit }, payload) {
    const { data } = await updateUser(payload);
    commit("updateUserInfo", data.user);
    return data.user;
  },
};
